<?php
namespace control;

/*
*公客池
*/

class clientPoolClass extends adIndexClass
{
    private const title = '公客池';
    private const page = 'clientPool';
    private const table = 'kehu';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'pool'          => [
                        'name'  => L('client.edit.pool'),
                        'width' => 200,
                    ],
                    'companyName' => [
                        'name'  => L('client.edit.companyName'),
                        'width' => 200,
                    ],
                    'contactName'  => [
                        'name'  => L('client.edit.contactName'),
                        'width' => 150,
                    ],
                    'contactTel'         => [
                        'name'  => L('client.edit.contactTel'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'landline'          => [
                        'name'  => L('client.edit.landline'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'source'          => [
                        'name'  => L('client.edit.source'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'time'          => [
                        'name'  => L('client.detail.time'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => L('client.edit.remark'),
                        'width' => 260,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('client.homeForm.companyName') => text(array("name" => "companyName")),
                    L('client.homeForm.pool')   => selectMultiple(array('table' => 'pool', 'sqlField' => 'name','where'=>"type = '公客池' and coid = '".self::$coid."' order by list asc", 'sqlId' => 'id', 'name' => 'poolId', 'class' => 'width200')),
                    L('client.homeForm.contactName') => text(array("name" => "contactName")),
                ],
                [
                    L('client.homeForm.contactTel')  => text(array("name" => "contactTel")),
                    L('client.homeForm.landline') => text(array("name" => "landline")),
                    L('client.homeForm.workFlow') => select(array("name" => "workFlow", "option" => explode("，", para("clientWorkFlow")))),
                ],
                [
                    L('client.edit.remark') => select(array("name" => "source", "option" => explode("，", para("clientSource")))),
                    L('client.detail.time') => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('clientPool.homeSearch.newTitle') . "','" . $url . "&fun=edit')\" class='spanButton'>".L('clientPool.homeSearch.new')."</span>\n
                       
                        <span onclick=\"layer('" . self::page . "','transfer',{})\" class='spanButton'>".L('clientPool.homeSearch.allot')."</span>\n
                        <span onclick=\"layer('" . self::page . "','pool',{})\" class='spanButton'>".L('clientPool.homeSearch.poolChange')."</span>\n";             // <span onclick=\"\" class='spanButton'>发送短信</span>\n
        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('clientPool.homeSearch.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(

            "companyName" => $this->post('companyName'),//客户名称
            "contactName" => $this->post('contactName'),//客户名称
            "contactTel" => $this->post('contactTel'),//联系手机
            "landline" => $this->post('landline'),//电话
            "text" => $this->post('text'),//备注
        );
        //全等查询数组
        $equal = array(
            'a.coid'=>self::$coid,
            "poolId" => $this->post('poolId'),
            "workFlow" => $this->post('workFlow'),//跟进情况
            "source" => $this->post('source'),//客户来源
        );
        //公私客
        $and = " and a.manager = ''";
        if (!$this->power(self::page, 'seeAll')) {
            $and .= " and if(b.isSee=1,(b.manager='" . self::$stid . "' or b.collaborator like '" . self::$stid . "'),b.manager='" . self::$stid . "')";
        }
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'),field: 'a.time');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(
                'time'=>'a.time'
            ),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a left join pool as b on a.poolId= b.id",
            'field' => "a.*",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['khid']),
                "detail" => array("title" => L('client.homeSearch.detail'), "click" => "newIframe('".L('client.homeSearch.detail')."','" . $url . "&id=" . $array['khid'] . "')"),
                "edit" => array("title" => L('client.homeSearch.edit'), "click" => "newIframe('" . L('client.homeSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['khid'] . "')"),
                'obtain' => array("title" => L('clientPool.homeSearch.obtain'), "click" => "layer('" . self::page . "','operate',{act:'obtain',id:'" . $array['khid'] . "'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "pool":
                        $pool = query('pool', " id = '$array[poolId]'");
                        $row[] = $pool['name'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " khid = '" . $id . "' ");
        $button[]  = [
            "name"  => L('public.save'),
            "type"  => "点击事件",
            "cla"   => $this->get('cla'),
            "fun"   => "subForm('" . self::page . "EditForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
            "post"  => ["id" => $this->get('id')],
            'style' => 'li-btn-blue-bg',
        ];
        $tags = '';
        $kehu_label = find(array('table' => 'kehu_label', 'where' => "targetId = '$info[khid]' order by list asc"));
        foreach ($kehu_label['array'] as $array) {
            $tag_detail = query('tag_detail', "id = '$array[tag_detail_id]'");
            $tags .= "<span class='background-color-gray' style='margin-right: 5px'>{$tag_detail['name']}<input name='labelMxId[]' type='hidden' value='{$tag_detail['id']}'></span>";
        }
        //表单
        $data['button'] = $this->tableShowButton($button);
        $data['html'] = $this->pageEdit([
            "table" => [
                L('client.edit.contactInfo') => [
                    [
                        must . L('client.edit.companyName')."：" => text(["name" => "companyName", 'class' => 'text', "value" => $info['companyName']]),
                        must . L('client.edit.nature')."：" => select(["name" => "nature", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientNature')), "value" => $info['nature']]),
                        must . L('client.edit.contactName')."：" => text(["name" => "contactName", 'class' => 'text', "value" => $info['contactName']]),
                        L('client.edit.contactIdentity')."：" => text(["name" => "contactIdentity", 'class' => 'text', "value" => $info['contactIdentity']]),
                    ],
                    [
                        L('client.edit.contactTel')."：" => text(["name" => "contactTel", 'class' => 'text', "value" => $info['contactTel']]),
                        L('client.edit.landline')."：" => text(["name" => "landline", 'class' => 'text', "value" => $info['landline']]),
                        L('client.edit.contactWx')."：" => text(["name" => "contactWx", 'class' => 'text', "value" => $info['contactWx']]),
                        L('client.edit.contactQQ')."：" => text(["name" => "contactQQ", 'class' => 'text', "value" => $info['contactQQ']]),
                    ],
                    [
                        L('client.edit.birthDay')."：" => text(["name" => "birthDay", 'class' => 'text', 'laydate' => [], "value" => self::null($info['birthDay'], false)]),
                        L('client.edit.website')."：" => text(["name" => "website", 'class' => 'text', "value" => $info['website']]),
                        L('client.edit.email')."：" => text(["name" => "email", 'class' => 'text', "value" => $info['email']]),
                        L('client.edit.address')."：" => text(["name" => "address", 'title' => L('client.edit.keyword'), 'class' => 'text', "value" => $info['address']]) . (componentClass::addressIco("layer('" . self::page . "','map',{})")) . hidden(array('name' => 'location', 'value' => $info['lng'] ? ($info['lat'] . ',' . $info['lng']) : '')),
                    ],
                ],
                L('client.edit.manageInfo') => [
                    [
                        L('client.edit.level')."：" => select(["name" => "level", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientLevel')), "value" => $info['level']]),
                        L('client.edit.classify')."：" => select(["name" => "classify", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientType')), "value" => $info['classify']]),
                        L('client.edit.industry')."：" => select(["name" => "industry", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientIndustry')), "value" => $info['industry']]),
                        L('client.edit.scale')."：" => select(["name" => "scale", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientScale')), "value" => $info['scale']]),
                    ],
                    [
                        L('client.edit.source')."：" => select(["name" => "source", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientSource')), "value" => $info['source']]),
                        L('client.edit.workFlow')."：" => select(["name" => "workFlow", 'class' => 'text', 'title' => L('client.edit.choice'), 'option' => explode('，', para('clientWorkFlow')), "value" => $info['workFlow']]),
                        L('client.edit.followTime')."：" => text(["name" => "followTime", 'laydate' => ['type' => 'datetime'], 'class' => 'text', "value" => $info['followTime']]),
                        L('client.edit.pool')."：" => selectMultiple(array('name' => 'poolId', 'title' => L('client.edit.choice'), 'where' => "type = '公客池' and coid='".self::$coid."'", 'table' => 'pool', 'sqlId' => 'id', 'sqlField' => 'name', 'value' => $info['poolId'])),
                    ],
                    [
                        L('client.edit.manager')."：" => selectMultiple(array('table' => 'staff', "title" => L('client.edit.choice'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'value' => $info['manager'])),
                        L('client.edit.collaborator')."：" => selectMultiple(array('table' => 'staff', 'where' => " stid !='$info[manager]'", 'multiple' => true, "title" => L('client.edit.choice'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'collaborator[]', 'value' => $info['collaborator'])),
                        L('client.edit.tags')."：" => "<span id='tags'>{$tags}</span><span class='spanButton' style='margin:0' onclick=\"layer('client','add_label',$('form[name=clientPoolEditForm]').serialize())\">".L('client.edit.addLabel')."</span>",
                    ],
                    [
                        L('client.edit.remark')."：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']])
                    ],
                ],
                L('client.edit.invoice') => [
                    array(
                        L('client.edit.invoiceCompany')."：" => text(array("name" => "invoiceCompany", "value" => $info['invoiceCompany'])),
                        L('client.edit.companyBank')."：" => text(array("name" => "companyBank", "value" => $info['companyBank'])),
                        L('client.edit.companyBankNum')."：" => text(array("name" => "companyBankNum", "value" => $info['companyBankNum'])),
                        L('client.edit.companyAddress')."：" => text(array("name" => "companyAddress", "value" => $info['companyAddress'])),
                    ),
                    array(
                        L('client.edit.companyNum')."：" => text(array("name" => "companyNum", "value" => $info['companyNum'])),
                        L('client.edit.postAddress')."：" => text(array("name" => "postAddress", "value" => $info['postAddress'])),
                    ),
                ]
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $info['khid'] ?: $id]),
        ]);

        $data['html'] .= <<<efo
<style>
 .font-bold{
   font-size: 14px;font-weight: bold
 }
</style>
<script>

$(function(){
    $("input[name='address']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=component&fun=getAddress',
        callback:function(data){
            $("[name='location']").val(data.location)
        }
    });

})
//选择标签
function confirm_label(){
     let serialize = $("[name='labelForm']").serialize();
     $('#clientAdd_label').hide();
     $.post(root+'control/adIndex.html?cla=client&fun=getTags', serialize, function (data) {
      $("#tags").empty().append(data.html)
    }, "json");
}
</script>
efo;

        //返回
        return $this->tab($data);
    }


    /**
     * 地图选址
     */
    public function map(): bool|string
    {
        $key = para('tencentMapKey');
        $sureWord = L('client.map.sure');
        $addressSelectionWord = L('client.map.addressSelection');
        $html = <<<efo
        <iframe id="mapPage" width="100%" height="90%" frameborder=0
            src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key={$key}&referer=myapp">
        </iframe>
        <div style="text-align: center;padding: 10px"><input onclick="$('#{$this->get('cla')}Map').hide()" class="button" type="button" value="$sureWord"></div>
        <script>
            window.addEventListener('message', function(event) {
                // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
                var loc = event.data;
                if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
                    //移除监听
                   event.stopPropagation();
                  $("[name='location']").val(loc.latlng.lat+','+loc.latlng.lng);
                  $("[name='address']").val(loc.poiaddress);
                }
            }, false);
        </script>
efo;

        return $this->layer(array("title" => $addressSelectionWord, "height" => 800, "width" => 1000, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $labelMxId = $this->post('labelMxId');//标签ID
        $field = [
            "contactName" => $this->post('contactName'),//联系人姓名
            "contactIdentity" => $this->post('contactIdentity'),//联系人身份
            "contactTel" => $this->post('contactTel'),//联系人手机号码
            "contactQQ" => $this->post('contactQQ'),//联系人QQ号码
            "contactWx" => $this->post('contactWx'),//联系人微信号
            "address" => $this->post('address'),
            "birthDay" => $this->post('birthDay'),
            "website" => $this->post('website'),
            "email" => $this->post('email'),
            "nature" => $this->post('nature'),
            "invoiceCompany" => $this->post('invoiceCompany'),
            "postAddress" => $this->post('postAddress'),
            "workFlow" => $this->post('workFlow'),//跟进状态
            "source" => $this->post('source'),//客户来源
            "level" => $this->post('level'),
            "classify" => $this->post('classify'),
            "scale" => $this->post('scale'),
            'followTime' => $this->post('followTime'),
            "industry" => $this->post('industry'),//所在行业
            "text" => $this->post('text'),
            'lat' => '',
            'lng' => '',
            'region' => '',
            "companyName" => $this->post('companyName'),//公司名称
            "companyNum" => $this->post('companyNum'),//纳税人识别号
            "companyBank" => $this->post('companyBank'),//公司开户银行
            "companyBankNum" => $this->post('companyBankNum'),//对公账号
            "landline" => $this->post('landline'),//公司座机
            "companyAddress" => $this->post('companyAddress'),//开票地址
            'poolId' => $this->post('poolId') ?: clientClass::defaulPoolId(),
            'manager' => $this->post('manager'),
            'collaborator' => $this->post('collaborator') && is_array($this->post('collaborator')) ? implode(',', array_unique($this->post('collaborator'))) : '',
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        ];
        $annotation = [
            'companyName' => L('client.editEdit.companyName'),
            'nature' => L('client.editEdit.nature'),
            "contactTel" => L('client.editEdit.contactTel'),
        ];
        $rules = [
            'companyName' => 'required',
            'nature' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " khid = '$id' ";
        $info = query(self::table, $where);
        $repeat = array(
            "khid" => $id,
            "field" => $field,
            "name" => array("contactQQ" => L('client.editEdit.contact_qq'), "companyName" => L('client.editEdit.company_name'), "companyNum" => L('client.editEdit.tax_number')),
        );
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('clientPool.editEdit.power');
        } elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
            $json['warn'] = L('client.editEdit.emailError');
        } elseif (!empty($field['contactQQ']) && preg_match(checkInteger, $field['contactQQ']) == 0) {
            $json['warn'] = L('client.editEdit.qqError');
        } elseif (!empty($field['website']) && preg_match(checkUrl, $field['website']) == 0) {
            $json['warn'] = L('client.editEdit.websiteError');
        } elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
            $json['warn'] = L('client.editEdit.collaboratorError');
        } elseif ($warn = $this->repeat($repeat)) {
            $json['warn'] = $warn;
        } elseif (static::total(array('table' => self::table, 'where' => "companyName = '$field[companyName]' and khid !='$id'")) > 0) {
            $json['warn'] = L('client.editEdit.nameRepeat');
        } else {
            //查看范围
            $field['see'] = implode(',', array_unique(array_merge(explode(',', $field['collaborator']), [$field['manager']])));
            if ($this->post('location')) {
                $location = explode(',', $this->post('location'));
                $field['lat'] = $location[0];
                $field['lng'] = $location[1];
                $region = componentClass::coordinateToAddr($field['lat'], $field['lng']);
                if ($region['err_code'] == 0) {
                    $field['region'] = $region['data']['address_component']['province'] . '-' . $region['data']['address_component']['city'] . '-' . $region['data']['address_component']['district'];
                }
            }

            if (!$info['khid']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'C',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'khid' => $id,
                    'coid'=>self::$coid,
                    'orderNo'=>$userNo,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $tagsText = '';
                //添加标签
                $kehu_label_id = [];
                if (!empty($labelMxId) && is_array($labelMxId)) {
                    foreach ($labelMxId as $tagsId) {
                        $kehu_label = query('kehu_label', "targetId = '$id' and tag_detail_id = '$tagsId'");
                        $tags_detail = query('tag_detail', "id = '$tagsId'");
                        $tags = query('tag', "id = '$tags_detail[orderId]'");
                        $tagsText .= $tags_detail['name'] . ',';
                        if (empty($kehu_label['id'])) {
                            $mid = self::getId();
                            $kehu_label_id[] = $mid;
                            static::insert(array(
                                'table' => 'kehu_label',
                                'field' => [
                                    'id' => $mid,
                                    'coid'=>self::$coid,
                                    'targetId' => $id,
                                    'tag_detail_id' => $tagsId,
                                    'tagId' => $tags['id'],
                                    'type' => 1,
                                    'time' => $this->time,
                                ]
                            ));
                        } else {
                            $kehu_label_id[] = $kehu_label['id'];
                        }
                    }
                }
                //删除无效关联的标签
                delete(array('table' => 'kehu_label', 'where' => "id not in ('" . implode("','", $kehu_label_id) . "') and targetId = '$id'"));
                update(array('table' => self::table, 'field' => ['tags' => $tagsText], 'where' => "khid = '$id'"));

                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('client.editEdit.log'));
                $this->logWrite($id, $type);
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*客户管理-客户详情页*/
    public function detail()
    {
        $kehu = query('kehu', "khid = '{$this->get('id')}'");
        if (empty($kehu['khid'])) {
            $html = L('clientPool.detail.empty');
        } else {
            //数据准备
            $pool = query('pool', " id = '$kehu[poolId]'");
            //菜单
            $data = array(
                "id" => $kehu['khid'],
                "title" => kong($kehu['companyName']),
            );
            //按钮
            $button = [];
            //这里需要判断客户池的人
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => L('clientPool.detail.edit'),
                    "type" => "顶部页卡",
                    "title" => L('clientPool.detail.edit'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $kehu['khid'],
                    'style' => 'li-btn-blue-bg',
                ];
                //按钮
                $button[] = [
                    "name" => L('clientPool.detail.allot'),
                    "type" => "点击事件",
                    "title" => L('clientPool.detail.transferToOthers'),
                    'fun' => "layer('" . self::page . "','transfer',{id:'" . $kehu['khid'] . "'})",
                ];
                //按钮
                $button[] = [
                    "name" => L('clientPool.detail.poolChange'),
                    "type" => "点击事件",
                    "title" => L('clientPool.detail.poolChange'),
                    'fun' => "layer('" . self::page . "','pool',{id:'" . $kehu['khid'] . "'})",
                ];
            }
            //按钮
            $button[] = [
                "name" => L('clientPool.detail.obtain'),
                "type" => "弹出层",
                "cla" => $this->get('cla'),
                "fun" => "operate",
                "post" => ["act" => 'obtain', "id" => $kehu['khid']],
            ];
            if ($this->power(self::page, "del")) {
                //按钮
                $button[] = [
                    "name" => L('clientPool.detail.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $kehu['khid']],
                ];
            }
            /******标签*********/
            $tags = '';
            $kehu_label = find(array('table' => 'kehu_label', 'where' => "targetId = '$kehu[khid]' order by list asc"));
            foreach ($kehu_label['array'] as $array) {
                $tag_detail = query('tag_detail', "id = '$array[tag_detail_id]'");
                $tags .= "<span class='background-color-gray' style='margin-right: 5px'>{$tag_detail['name']}</span>";
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "联系信息" => array(
                    array(
                        L('client.edit.companyName') => $kehu['companyName'],
                        L('client.edit.nature') => $kehu['nature'],
                        L('client.edit.contactName') => $kehu['contactName'],
                        L('client.edit.contactIdentity') => $kehu['contactIdentity'],
                    ),
                    array(
                        L('client.edit.contactTel') => $kehu['contactTel'],
                        L('client.edit.landline') => $kehu['landline'],
                        L('client.edit.contactWx') => $kehu['contactWx'],
                        L('client.edit.contactQQ') => $kehu['contactQQ'],
                    ),
                    array(
                        L('client.edit.birthDay') => self::null($kehu['birthDay']),
                        L('client.edit.website') => $kehu['website'],
                        L('client.edit.email') => $kehu['email'],
                        L('client.edit.address') => $kehu['address'],
                    ),
                ),
                L('client.edit.manageInfo') => array(
                    array(
                        L('client.edit.level') => $kehu['level'],
                        L('client.edit.classify') => $kehu['classify'],
                        L('client.edit.industry') => $kehu['industry'],
                        L('client.edit.scale') => $kehu['scale'],
                    ),
                    array(
                        L('client.edit.source') => $kehu['source'],
                        L('client.edit.tags') => $tags,
                        L('client.edit.workFlow') => $kehu['workFlow'],
                        L('client.edit.followTime') => self::null($kehu['followTime']),
                    ),
                    array(
                        L('client.edit.pool') => clueClass::setBackGroundColorGray($pool['name']),

                    ),
                    array(
                        L('client.edit.remark') => pre($kehu['text']),
                    ),
                ),
                L('client.edit.invoice') => array(
                    array(
                        L('client.edit.invoiceCompany') => $kehu['invoiceCompany'],
                        L('client.edit.companyBank') => $kehu['companyBank'],
                        L('client.edit.companyBankNum') => $kehu['companyBankNum'],
                        L('client.edit.companyAddress') => $kehu['companyAddress'],
                    ),
                    array(
                        L('client.edit.companyNum') => $kehu['companyNum'],
                        L('client.edit.postAddress') => $kehu['postAddress'],
                    ),
                ),
                L('client.detail.sys') => array(
                    array(
                        L('client.detail.stid') => self::findStaff($kehu['stid']),
                        L('client.detail.time') => $kehu['time'],
                        L('client.detail.updateTime') => $kehu['updateTime'],
                    ),
                ),
            ));
            //生成页面s
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * 转到客户池
     */
    public function pool()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('client.pool.clientPool')."：" => selectMultiple(array('table' => 'pool', 'where' => "type = '公客池' and coid='".self::$coid."'", "title" => L('client.pool.choice'), 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'poolId')),
            ),
        )
        ));
        //返回
        return $this->layer(array("title" => L('client.pool.transferToClientPool'), 'winFix' => true, "height" => 200, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     *  转到客户池编辑
     */
    public function poolEdit()
    {
        $listId = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $poolId = $this->post('poolId');
        $pool = query('pool', "id = '$poolId'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('clientPool.poolEdit.power');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('clientPool.poolEdit.emptyClient');
        } elseif (empty($pool['id'])) {
            $json['warn'] = L('clientPool.poolEdit.empty');
        } else {
            $x = 0;
            foreach ($listId as $id) {
                //客户
                $info = query(self::table, " khid = '$id'");
//                if ($info['manager'] == self::$stid) {
                $warn = update(array(
                    'table' => self::table,
                    'field' => [
                        'poolId' => $pool['id'],
                    ],
                    'where' => "khid = '$id'"
                ));
                if (in_array($warn, ['新增成功', '更新成功'])) {
                    $x++;
                    $text = str_replace(['{{staffName}}','{{companyName}}','{{id}}','{{pool}}'], [$this->control['name'],$info['companyName'],$id,$pool['name']], L('client.poolEdit.logText'));
                    $this->logText(["type" => self::page, "text" => $text]);
                    //日志
                    $this->logWrite($id, '添加到客户池', str_replace(['{{staffName}}','{{pool}}'], [$this->control['name'],$pool['name']], L('client.poolEdit.logWrite')));
                }
//                } else {
//                    $text = $this->control['name'] . "把" . self::title . "【{$info['companyName']}】添加到客户池失败：不是负责人";
//                    $this->logText(["type" => self::page, "text" => $text]);
//                }

            }
            $json['warn'] = 2;
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('client.poolEdit.warn'));
        }
        return json_encode($json, 320);
    }

    /**
     * 转交
     */
    public function transfer()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('client.transfer.manager')."：" => selectMultiple(array("title" => L('client.transfer.choice'), 'option' => $this->staffOption(), 'name' => 'manager')),
            ),
            array(
                L('client.transfer.collaborator')."：" => selectMultiple(array('table' => 'staff', 'multiple' => true, "title" => L('client.transfer.choice'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'collaborator[]')),
            ),

        )
        ));
        //返回
        return $this->layer(array("title" => L('client.transfer.transmit'), 'winFix' => true, "height" => 260, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 获取转交给他人的选项
     * @return array
     */
    public function staffOption(): array
    {
        $option['空'] = L('clientPool.staffOption.empty');
        $result = find(array('table' => 'staff', 'where' => "state in ('试用','转正')"));
        foreach ($result['array'] as $array) {
            $option[$array['stid']] = $array['name'];
        }
        return $option;
    }


    /**
     * 转交编辑
     */
    public function transferEdit(): bool|string
    {
        $listId = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $field = array(
            'lastFollowTime' => '',
            'manager' => $this->post('manager') == '空' ? '' : $this->post('manager'),
            'collaborator' => $this->post('collaborator') && is_array($this->post('collaborator')) ? implode(',', array_unique($this->post('collaborator'))) : '',
        );
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('clientPool.transferEdit.power');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('clientPool.transferEdit.notFindClient');
        } elseif (empty($field['manager'])) {
            $json['warn'] = L('clientPool.transferEdit.choiceManage');
        } elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
            $json['warn'] = L('clientPool.transferEdit.choiceError');
        } else {
            $x = 0;
            //查看范围
            $field['see'] = implode(',', array_unique(array_filter(array_merge([$field['manager']], explode(',', $field['collaborator'])))));
            $field['collaborator'] = empty($field['manager']) ? '' : $field['collaborator'];
            $manager = query('staff', "stid = '$field[manager]'");
            foreach ($listId as $id) {
                $info = query(self::table, " khid = '$id'");
                $pool = query('pool', "id = '$info[poolId]'");
                if ($pool['manager'] == self::$stid) {
                    if ($pool['isCooper']) {
                        //设置客户池负责人为协作人
                        $field['collaborator'] = array_unique(array_filter(array_merge(explode(',', $field['collaborator']), [$pool['manager']])));
                        $field['see'] = implode(',', array_unique(array_filter(array_merge([$field['manager']], $field['collaborator']))));
                        $field['collaborator'] = implode(',', $field['collaborator']);
                    }
                    $field['disTime'] = $this->time;
                    $warn = update(array(
                        'table' => self::table,
                        'field' => $field,
                        'where' => " khid = '$id'"
                    ));
                    if ($warn == '更新成功') {
                        $x++;
                        $this->logWrite($id, '分配');
                        $text = str_replace(['{{staffName}}','{{companyName}}','{{id}}','{{manage}}'], [$this->control['name'],$info['companyName'],$id,$manager['name']], L('clientPool.transferEdit.log'));
                        $this->logText(["type" => self::page, "text" => $text]);
                    }
                } else {
                    $text = str_replace(['{{staffName}}','{{companyName}}'], [$this->control['name'],$info['companyName']], L('clientPool.transferEdit.failLog'));
                    $this->logText(["type" => self::page, "text" => $text]);
                }
            }
            $json['warn'] = 2;
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('clientPool.transferEdit.warn'));
            $json['href'] = root.'control/adIndex.html?cla='.self::page.'&fun=home';
        }
        return json_encode($json, 320);
    }

    /*客户资料排重*/
    public function repeat($data)
    {
        foreach ($data['name'] as $name => $explain) {
            if (!empty($data['field'][$name])) {
                //客户排重查询
                $kehu = query("kehu", $name . " = '" . $data['field'][$name] . "' and khid != '$data[khid]' ");
                if (!empty($kehu['khid'])) {
                    if ($kehu['stid'] == "公客") {
                        $follow = L('clientPool.repeat.public');
                    } else {
                        $staff = query("staff", " stid = '$kehu[stid]' ");
                        $follow = str_replace(['{{staffName}}'], [$staff['name']], L('clientPool.repeat.follow'));
                    }
                    return str_replace(['{{companyName}}','{{explain}}','{{name}}'], [$kehu['companyName'],$explain,$data['field'][$name]], L('clientPool.repeat.log')) . $follow;
                }
            }
        }
        return false;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            case 'obtain':
                //获取
                $act = 'see';
                $msg = L('clientPool.operate.public');
                $title = L('clientPool.operate.obtain');
                $function = 'obtain';
                $form = self::page . 'OperateForm, listForm';
                $word = true;

                break;
            default:
                $act = 'del';
                $msg = L('clientPool.operate.del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('clientPool.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 获取
     */
    public function obtain()
    {
        $id = $this->post('id');
        //客户
        $info = query(self::table, " khid = '$id'");
        //先判断他是不是此客户池的能查看到的人
        if (empty($info['khid'])) {
            $json['warn'] = L('clientPool.obtain.empty');
        } elseif (!empty($info['manager'])) {
            $json['warn'] = L('clientPool.obtain.obtainOther');
        } else {
            $pool = query('pool', "id = '$info[poolId]'");
            $field = [
                'manager' => self::$stid,
                'see' => self::$stid,
                'collaborator' => '',
                'lastFollowTime' => '',
                'disTime' => $this->time,
                'updateTime' => $this->time,
            ];
            if ($pool['isCooper']) {
                //设置线索池负责人为协作人
                $field['collaborator'] = array_unique(array_filter(array_merge(explode(',', $field['collaborator']), [$pool['manager']])));
                $field['see'] = implode(',', array_unique(array_filter(array_merge([$field['manager']], $field['collaborator']))));
                $field['collaborator'] = implode(',', $field['collaborator']);
            }
            $warn = update(array(
                'table' => self::table,
                'field' => $field,
                'where' => " khid = '$info[khid]'"
            ));
            if ($warn == '更新成功') {
                $text = str_replace(['{{staffName}}','{{companyName}}','{{id}}'], [$this->control['name'],$info['companyName'],$id], L('clientPool.obtain.logText'));
                $this->logText(["type" => self::page, "text" => $text]);
                //日志
                $this->logWrite($id, '获取', str_replace(['{{staffName}}'], [$this->control['name']], L('clientPool.obtain.logWrite')));
            }
            $json['warn'] = 2;
            $_SESSION['warn'] = L('clientPool.obtain.success');
            $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=home';
        }
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('clientPool.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('clientPool.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " khid = '$id' ");
                $result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                foreach ($result['array'] as $file) {
                    fileDelete($file['src']);
                }
                //删除附件
                delete(array("table" => "file", "where" => " targetId = '$id' "));
                //删除标签
                delete(array("table" => "kehu_label", "where" => " targetId = '$id' "));
                //删除跟进记录
                delete(array("table" => "follow", "where" => " targetId = '$id' "));
                //删除操作日志
                delete(array("table" => "clue_log", "where" => " orderId = '$id' "));
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " khid = '$id' "));
                //返回
                $warn = L('clientPool.delete.success');
                $x++;
                $text .= str_replace(['{{khid}}'], [$info['khid']], L('clientPool.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('clientPool.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('clientPool.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 日志写入
     */
    public function logWrite($id, $type, $text = '')
    {
        $info = query(self::table, " khid = '$id'");
        insert(array(
            'table' => 'clue_log',
            'field' => [
                'id' => self::getId(),
                'coid'=>self::$coid,
                'orderId' => $id,
                'classify' => '客户',
                'type' => $type,
                'text' => $text ?: str_replace(['{{staffName}}','{{type}}','{{companyName}}'], [$this->control['name'],$type,$info['companyName']], L('clientPool.logWrite.text')),
                'staffName' => $this->control['name'],
                'stid' => $this->control['stid'],
                'time' => $this->time
            ]
        ));
    }


    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = L('clientPool.downloadModel.power');
        }  else {
            $exampleData[] = ['重庆雨木科技','民营企业','邱女士','行政','13000000000','44340001','wechat001','10001','1995-01-01','www.yumukeji.com','001@yumukeji.com',
                '重庆市南岸区国际社区','A类','互联网','软件信息行业','100人以下','官网','初次联系','2021-01-01 00:00:00','默认客户池','张三','YM202111220001','李四,王五','YM202111220002,YM202111220003',
                '重庆雨木科技有限责任公司','中国工商银行','000000000001','重庆市 44310001','0002121111111','重庆市南岸区国际社区','(样例数据，导入时请删除本条数据)'];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '客户名称'=>$example[0],
                            '性质'=>$example[1],
                            '常用联系人姓名'=>$example[2],
                            '常用联系人职务'=>$example[3],
                            '常用联系人手机'=>$example[4],
                            '常用联系人电话'=>$example[5],
                            '常用联系人微信'=>$example[6],
                            '常用联系人QQ'=>$example[7],
                            '生日'=>$example[8],
                            '网址'=>$example[9],
                            '邮箱'=>$example[10],
                            '地址'=>$example[11],
                            '客户级别'=>$example[12],
                            '客户类别'=>$example[13],
                            '所属行业'=>$example[14],
                            '人员规模'=>$example[15],
                            '来源'=>$example[16],
                            '跟进状态'=>$example[17],
                            '下次跟进时间'=>$example[18],
                            '所属客户池'=>$example[19],
                            '负责人'=>$example[20],
                            '负责人编号'=>$example[21],
                            '协作人'=>$example[22],
                            '协作人编号'=>$example[23],
                            '开户行'=>$example[24],
                            '银行账号'=>$example[25],
                            '注册地址、电话'=>$example[26],
                            '开票公司名称'=>$example[27],
                            '纳税人识别号'=>$example[28],
                            '邮寄地址'=>$example[29],
                            '备注'=>$example[30],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }


            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('clientPool.downloadModel.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = L('clientPool.importData.power');
        }  else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $manager = query("staff", "orderNo = '$cell[负责人编号]'");
                    $partner = explode(',', $cell['协作人编号']);
                    $collaborator = [];
                    foreach ($partner as $stid) {
                        $staff = query('staff', "orderNo = '$stid'");
                        if (!empty($staff['stid'])){
                            $collaborator[] = $staff['stid'];
                        }
                    }

                    $pool = query('pool', "name = '$cell[所属客户池]' and type = '公客池' and coid='".self::$coid."'");

                    $id = self::getId();
                    $field = [
                        'coid'=>self::$coid,
                        'khid' => $id,
                        "companyName" => $cell['客户名称'],//公司名称
                        "nature" => $cell['性质'],
                        "contactName" => $cell['常用联系人姓名'],//联系人姓名
                        "contactIdentity" => $cell['常用联系人职务'],//联系人身份
                        "contactTel" => $cell['常用联系人手机'],//联系人手机号码
                        "landline" => $cell['常用联系人电话'],//公司座机
                        "contactQQ" => $cell['常用联系人QQ'],//联系人QQ号码
                        "contactWx" => $cell['常用联系人微信'],//联系人微信号
                        "address" => $cell['地址'],
                        "birthDay" => $cell['生日'],
                        "website" => $cell['网址'],
                        "email" => $cell['邮箱'],
                        "level" => $cell['客户级别'],
                        "classify" => $cell['客户类别'],
                        "scale" => $cell['人员规模'],
                        'followTime' => $cell['下次跟进时间'],
                        "industry" => $cell['所属行业'],//所在行业
                        "invoiceCompany" => $cell['开票公司名称'],
                        "postAddress" => $cell['邮寄地址'],
                        "workFlow" => $cell['跟进状态'],
                        "source" => $cell['来源'],
                        "text" => $cell['备注'],
                        "companyNum" => $cell['纳税人识别号'],//纳税人识别号
                        "companyBank" => $cell['开户行'],
                        "companyBankNum" => $cell['银行账号'],//对公账号
                        "companyAddress" => $cell['注册地址、电话'],//开票地址
                        'poolId' => $pool['id']?:clientClass::defaulPoolId(),
                        'manager' => $cell['负责人编号']?$manager['stid']:'',
                        'collaborator' => implode(',', array_filter(array_unique($collaborator))),
                        "updateTime" => date("Y-m-d H:i:s"),//更新时间
                        'time' => $this->time,
                    ];
                    $annotation = [
                        'companyName' => L('clientPool.importData.companyName'),
                        'nature' => L('clientPool.importData.nature'),
                        "contactTel" => L('clientPool.importData.contactTel'),
                    ];
                    $rules = [
                        'companyName' => 'required',
                        'nature' => 'required',
                        "contactTel" => 'required',
                    ];
                    $repeat = array(
                        "khid" => $id,
                        "field" => $field,
                        "name" => array("contactQQ" => L('clientPool.importData.contact_qq'), "companyName" => L('clientPool.importData.company_name'), "companyNum" => L('clientPool.importData.tax_number')),
                    );
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if (!empty($cell['负责人编号']) && !$manager['stid']) {
                        $text .= str_replace(['{{i}}'], [$row_list], L('clientPool.importData.staffEmtpy'));
                    } elseif ($result === false) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('clientPool.importData.row')) . $vt->getErrs()[0];
                    } elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('clientPool.importData.emailError'));
                    } elseif (!empty($field['contactQQ']) && preg_match(checkInteger, $field['contactQQ']) == 0) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('clientPool.importData.qqError'));
                    } elseif (!empty($field['website']) && preg_match(checkUrl, $field['website']) == 0) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('clientPool.importData.websiteError'));
                    } elseif (!empty($cell['所属客户池']) && empty($pool['id'])) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('clientPool.importData.pollEmpty'));
                    } elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('clientPool.importData.collaborator'));
                    } elseif ($warn = $this->repeat($repeat)) {
                        $text .= "\n".str_replace(['{{i}}'], [$row_list], L('clientPool.importData.row')) . $warn;
                    } else {
                        //查看范围
                        $field['see'] = implode(',',array_filter(array_unique(array_merge(explode(',', $field['collaborator']), [$field['manager']]))));
                        if (!empty($field['address'])){
                            //解析地址信息 得到经纬度和省市区
                            $locationRes= componentClass::addrToCoordinate($field['address']);
                            if ($locationRes['err_code'] == 0) {
                                $field['lat'] = $locationRes['data']['location']['lat'];
                                $field['lng'] = $locationRes['data']['location']['lng'];
                                $region = componentClass::coordinateToAddr($field['lat'], $field['lng']);
                                if ($region['err_code'] == 0) {
                                    $field['region'] = $region['data']['address_component']['province'] . '-' . $region['data']['address_component']['city'] . '-' . $region['data']['address_component']['district'];
                                }
                            }
                        }
                        $userNo = codeTemplateClass::generateCode(self::page,[
                            'prefix' => 'C',
                            'table' => self::table,
                            'field' => 'orderNo',
                            'where' => '',
                        ],$field);
                        $field['orderNo']=$userNo;
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行：导入失败：编辑失败<br>";
                        }
                    }
                }
            }

            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = str_replace(['{{staffName}}','{{fileName}}'], [$this->control['name'],$_FILES['file']['name']], L('clientPool.importData.log')) . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('clientPool.exportData.power');
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table . " as a left join pool as b on a.poolId= b.id",
                    'field' => "a.*",
                    "where" => "a.khid in ('".implode("','", $checkedId)."') order by a.time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $pool = query('pool', " id = '$array[poolId]'");
                $tags = '';
                $kehu_label = find(array('table' => 'kehu_label', 'where'=>"targetId = '$array[khid]' order by list asc"));
                foreach ($kehu_label['array'] as $val) {
                    $tag_detail = query('tag_detail', "id = '$val[tag_detail_id]'");
                    $tags .= $tag_detail['name'].',';
                }
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '客户名称'=>$array['companyName'],
                            '性质'=>$array['nature'],
                            '常用联系人姓名'=>$array['contactName'],
                            '常用联系人职务'=>$array['contactIdentity'],
                            '常用联系人手机'=>$array['contactTel'],
                            '常用联系人电话'=>$array['landline'],
                            '常用联系人微信'=>$array['contactWx'],
                            '常用联系人QQ'=>$array['contactQQ'],
                            '生日'=>$array['birthDay'],
                            '网址'=>$array['website'],
                            '邮箱'=>$array['email'],
                            '地址'=>$array['address'],
                            '客户级别'=>$array['level'],
                            '客户类别'=>$array['classify'],
                            '所属行业'=>$array['scale'],
                            '人员规模'=>$array['source'],
                            '来源'=>$array['workFlow'],
                            '跟进状态'=>$array['followTime'],
                            '下次跟进时间'=> '',
                            '标签'=>$tags,
                            '所属客户池'=> $pool['name'],
                            '负责人'=> self::findStaff($array['manager']),
                            '协作人'=> clueClass::showMember($array['collaborator'], 2),
                            '开票公司'=>$array['invoiceCompany'],
                            '开户行'=>$array['companyBank'],
                            '银行账号'=>$array['companyBankNum'],
                            '注册地址、电话'=>$array['companyAddress'],
                            '纳税人识别号'=>$array['companyNum'],
                            '邮寄地址'=>$array['postAddress'],
                            '备注'=>$array['text'],
                            '创建人'=> self::findStaff($array['stid']),
                            '更新时间'=>$array['updateTime'],
                            '创建时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('clientPool.exportData.text'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('clientPool.exportData.fileName').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default => [
                [
                    'columnName' => '客户名称',
                    'aliasName'  => '客户名称',
                    'list'       => 1,
                    'isMust'     => true,
                ],
                [
                    'columnName' => '性质',
                    'aliasName'  => '性质',
                    'list'       => 2,
                    'isMust'     => true,
                ],
                [
                    'columnName' => '常用联系人姓名',
                    'aliasName'  => '常用联系人姓名',
                    'list'       => 3,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '常用联系人职务',
                    'aliasName'  => '常用联系人职务',
                    'list'       => 4,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '常用联系人手机',
                    'aliasName'  => '常用联系人手机',
                    'list'       => 5,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '常用联系人电话',
                    'aliasName'  => '常用联系人电话',
                    'list'       => 6,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '常用联系人微信',
                    'aliasName'  => '常用联系人微信',
                    'list'       => 7,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '常用联系人QQ',
                    'aliasName'  => '常用联系人QQ',
                    'list'       => 8,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '生日',
                    'aliasName'  => '生日',
                    'list'       => 9,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '网址',
                    'aliasName'  => '网址',
                    'list'       => 10,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '邮箱',
                    'aliasName'  => '邮箱',
                    'list'       => 11,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '地址',
                    'aliasName'  => '地址',
                    'list'       => 12,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '客户级别',
                    'aliasName'  => '客户级别',
                    'list'       => 13,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '客户类别',
                    'aliasName'  => '客户类别',
                    'list'       => 14,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '所属行业',
                    'aliasName'  => '所属行业',
                    'list'       => 15,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '人员规模',
                    'aliasName'  => '人员规模',
                    'list'       => 16,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '来源',
                    'aliasName'  => '来源',
                    'list'       => 17,
                    'isMust'     => false,
                ],
                [
                    'columnName' => '跟进状态',
                    'aliasName'  => '跟进状态',

                    'isMust' => false,
                ],
                [
                    'columnName' => '下次跟进时间',
                    'aliasName'  => '下次跟进时间',

                    'isMust' => false,
                ],
                [
                    'columnName' => '所属客户池',
                    'aliasName'  => '所属客户池',

                    'isMust' => false,
                ],
                [
                    'columnName' => '负责人',
                    'aliasName'  => '负责人',

                    'isMust' => false,
                ],
                [
                    'columnName' => '负责人编号',
                    'aliasName'  => '负责人编号',

                    'isMust' => true,
                ],
                [
                    'columnName' => '协作人',
                    'aliasName'  => '协作人',

                    'isMust' => false,
                ],
                [
                    'columnName' => '协作人编号',
                    'aliasName'  => '协作人编号(多个用英文逗号隔开)',

                    'isMust' => false,
                ],
                [
                    'columnName' => '开票公司名称',
                    'aliasName'  => '开票公司名称',

                    'isMust' => false,
                ],
                [
                    'columnName' => '开户行',
                    'aliasName'  => '开户行',

                    'isMust' => false,
                ],
                [
                    'columnName' => '银行账号',
                    'aliasName'  => '银行账号',

                    'isMust' => false,
                ],
                [
                    'columnName' => '注册地址、电话',
                    'aliasName'  => '注册地址、电话',

                    'isMust' => false,
                ],
                [
                    'columnName' => '纳税人识别号',
                    'aliasName'  => '纳税人识别号',

                    'isMust' => false,
                ],
                [
                    'columnName' => '邮寄地址',
                    'aliasName'  => '邮寄地址',

                    'isMust' => false,
                ],
                [
                    'columnName' => '备注',
                    'aliasName'  => '备注',

                    'isMust' => false,
                ],
            ]
        };
    }
        /**
         * 导出模板字段初始化
         * @return array[]
         */
        public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                ],
                [
                    'columnName'=>'性质',
                    'aliasName'=>'性质',
                ],
                [
                    'columnName'=>'常用联系人姓名',
                    'aliasName'=>'常用联系人姓名',
                ],
                [
                    'columnName'=>'常用联系人职务',
                    'aliasName'=>'常用联系人职务',
                ],
                [
                    'columnName'=>'常用联系人手机',
                    'aliasName'=>'常用联系人手机',
                ],
                [
                    'columnName'=>'常用联系人电话',
                    'aliasName'=>'常用联系人电话',
                ],
                [
                    'columnName'=>'常用联系人微信',
                    'aliasName'=>'常用联系人微信',
                ],
                [
                    'columnName'=>'常用联系人QQ',
                    'aliasName'=>'常用联系人QQ',
                ],
                [
                    'columnName'=>'生日',
                    'aliasName'=>'生日',
                ],
                [
                    'columnName'=>'网址',
                    'aliasName'=>'网址',
                ],
                [
                    'columnName'=>'邮箱',
                    'aliasName'=>'邮箱',
                ],
                [
                    'columnName'=>'地址',
                    'aliasName'=>'地址',
                ],
                [
                    'columnName'=>'客户级别',
                    'aliasName'=>'客户级别',
                ],
                [
                    'columnName'=>'客户类别',
                    'aliasName'=>'客户类别',
                ],
                [
                    'columnName'=>'所属行业',
                    'aliasName'=>'所属行业',
                ],
                [
                    'columnName'=>'人员规模',
                    'aliasName'=>'人员规模',
                ],
                [
                    'columnName'=>'来源',
                    'aliasName'=>'来源',
                ],
                [
                    'columnName'=>'跟进状态',
                    'aliasName'=>'跟进状态',
                ],
                [
                    'columnName'=>'下次跟进时间',
                    'aliasName'=>'下次跟进时间',
                ],
                [
                    'columnName'=>'标签',
                    'aliasName'=>'标签',
                ],
                [
                    'columnName'=>'所属客户池',
                    'aliasName'=>'所属客户池',
                ],
                [
                    'columnName'=>'负责人',
                    'aliasName'=>'负责人',
                ],
                [
                    'columnName'=>'协作人',
                    'aliasName'=>'协作人',
                ],
                [
                    'columnName'=>'开票公司名称',
                    'aliasName'=>'开票公司名称',
                ],
                [
                    'columnName'=>'开户行',
                    'aliasName'=>'开户行',
                ],
                [
                    'columnName'=>'银行账号',
                    'aliasName'=>'银行账号',
                ],
                [
                    'columnName'=>'注册地址、电话',
                    'aliasName'=>'注册地址、电话',
                ],
                [
                    'columnName'=>'纳税人识别号',
                    'aliasName'=>'纳税人识别号',
                ],
                [
                    'columnName'=>'邮寄地址',
                    'aliasName'=>'邮寄地址',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'创建人',
                    'aliasName'=>'创建人',
                ],
                [
                    'columnName'=>'更新时间',
                    'aliasName'=>'更新时间',
                ],
                [
                    'columnName'=>'创建时间',
                    'aliasName'=>'创建时间',
                ],
            ]
        };
    }
}
